package cn.uway.controller.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.uway.properties.CustomProperties;
import cn.uway.shiro.LoginCommand;
import cn.uway.utils.PubValue;

@Controller
@RequestMapping("/ajax")
public class AjaxController {	
	
	protected  Logger logger = LoggerFactory.getLogger(this.getClass());	
	
	//获取配置信息
	@Autowired
	private  CustomProperties customProperties;
		
	@RequestMapping(value ="/login" /*, method=RequestMethod.POST */)
    public void loginCheck(HttpServletRequest request, HttpServletResponse response, LoginCommand command, BindingResult errors) {
		UsernamePasswordToken token = new UsernamePasswordToken(command.getUsername(), command.getPassword(),request.getRemoteAddr());
		String msg = null;
		String json = "";
		try {
			SecurityUtils.getSubject().login(token);
		} 
		catch (Exception e) {
			logger.debug("Error authenticating.", e);
			if (e instanceof LockedAccountException) {
				msg = "账户已锁定！";
			} else if (e instanceof IncorrectCredentialsException) {
				msg = "账户名或密码错误！";
			} 
			else if (e instanceof ExcessiveAttemptsException) {
				msg = "用户名或密码错误超过5次！";
			}            
            else if (e instanceof AccountException) {
            	msg = e.getMessage();
			}
            else if (e instanceof AuthenticationException) {
				msg = "认证失败！";
			}
			if (StringUtils.isEmpty(msg)) {
				msg = "用户名密码错误！";
			}
			errors.reject("error.invalidLogin","The username or password was not correct.");
		}
		if (errors.hasErrors()) {
			json = "{\"RET_CODE\":\"FAILED\", \"RET_MSG\":\"" +msg+ "\"}";
		} 
		else{
			String loginId = (String)request.getSession().getAttribute(PubValue.SESSIONKEY_LOGIN_ID);
			json = "{\"RET_CODE\":\"SUCCESS\", \"RET_MSG\":\"登录成功\", \"LOGIN_ID\":\""+loginId+"\"}";
		}
		
		writeToPage(json ,  response);
    }
	
	
	
	public void writeToPage(String content, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "text/javascript;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");  
		response.setHeader("Cache-Control", "no-cache");  
		response.setDateHeader("Expires", 0); 		
		PrintWriter pw = null;		
		try {
			pw = response.getWriter();
			pw.write(content);
		} 
		catch (IOException e) {
			logger.warn("write to page error: ", e);
		} finally {
			if (pw != null) {
				pw.flush();
				pw.close();
			}
		}
	}  	 
	
}
